package com.example.quiz.controller;

import com.example.quiz.common.Result;
import com.example.quiz.common.TrainingMode;
import com.example.quiz.model.Question;
import com.example.quiz.model.User;
import com.example.quiz.service.AnswerRecordService;
import com.example.quiz.service.QuestionService;
import com.example.quiz.service.CategoryService;
import com.example.quiz.service.WrongQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;

@Controller
@RequestMapping("/question")
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AnswerRecordService answerRecordService;

    @Autowired
    private WrongQuestionService wrongQuestionService;

    // 题目列表页面
    @GetMapping("/list")
    public String listPage() {

        return "question/list";
    }

    // 题目详情（答题）页面
    @GetMapping("/detail/{id}")
    public String detailPage(@PathVariable Long id, Model model, HttpSession session) {
        // 检查是否登录
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // 将要访问的页面URL存入session，登录后可以重定向回来
            session.setAttribute("redirectUrl", "/question/detail/" + id);
            return "redirect:/user/login";
        }

        Question question = questionService.getById(id);
        model.addAttribute("question", question);
        return "question/detail";
    }

    // 获取题目列表数据
    @GetMapping("/api/list")
    @ResponseBody
    public Result<Map<String, Object>> getQuestionList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) Long categoryId) {

        List<Question> questions = questionService.getPagedQuestions(page, size, categoryId, null);
        int total = questionService.getTotalCount(categoryId, null);

        Map<String, Object> data = new HashMap<>();
        data.put("list", questions);
        data.put("total", total);

        return Result.success(data);
    }

    // 获取题目详情数据
    @GetMapping("/api/detail/{id}")
    @ResponseBody
    public Result<Question> getQuestionDetail(@PathVariable Long id) {
        Question question = questionService.getById(id);
        if (question != null) {
            return Result.success(question);
        }
        return Result.error("题目不存在");
    }

    // 提交答案
    @PostMapping("/api/submit")
    @ResponseBody
    public Result<Map<String, Object>> submitAnswer(
            @RequestParam Long questionId,
            @RequestParam String answer,
            @RequestParam(defaultValue = "false") boolean isMultiple,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "请先登录");
        }

        Question question = questionService.getById(questionId);
        if (question == null) {
            return Result.error("题目不存在");
        }

        boolean isCorrect;
        if (isMultiple) {
            // 多选题答案比较
            String[] correctAnswers = question.getCorrectAnswers();
            String[] userAnswers = answer.split(",");
            Arrays.sort(correctAnswers);
            Arrays.sort(userAnswers);
            isCorrect = Arrays.equals(correctAnswers, userAnswers);
        } else {
            // 单选题答案比较
            isCorrect = question.getAnswer().equalsIgnoreCase(answer);
        }

        // 记录答题记录
        questionService.recordAnswer(user.getId(), questionId, answer, isCorrect);

        Map<String, Object> data = new HashMap<>();
        data.put("correct", isCorrect);
        data.put("answer", answer);
        // 统一处理答案格式
        if (isMultiple) {
            data.put("correctAnswer", String.join(",", question.getCorrectAnswers()));
        } else {
            data.put("correctAnswer", question.getAnswer());
        }

        return Result.success(data);
    }

    @GetMapping("/training/{mode}")
    public String trainingPage(@PathVariable String mode,
            @RequestParam(required = false) Long categoryId,
            Model model) {
        model.addAttribute("mode", mode);
        return "question/training";
    }

    @GetMapping("/api/training/progress")
    @ResponseBody
    public Result<Map<String, Object>> getTrainingProgress(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("请先登录");
        }

        Map<String, Object> data = new HashMap<>();
        data.put("totalAnswered", answerRecordService.getTotalCount(user.getId()));
        data.put("correctCount", answerRecordService.getCorrectCount(user.getId()));
        data.put("wrongCount", wrongQuestionService.getTotalCount(user.getId()));

        return Result.success(data);
    }

    @GetMapping("/api/training/{mode}")
    @ResponseBody
    public Result<List<Question>> getTrainingQuestions(
            @PathVariable String mode,
            @RequestParam(required = false) Long categoryId,
            HttpSession session) {

        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error(401, "请先登录");
        }

        List<Question> questions;
        try {
            switch (TrainingMode.valueOf(mode.toUpperCase())) {
                case SEQUENTIAL:
                    questions = questionService.getPagedQuestions(1, 10, null, null);
                    break;
                case RANDOM:
                    questions = questionService.getRandomQuestions(10);
                    break;
                case CATEGORY:
                    if (categoryId == null) {
                        return Result.error("请选择分类");
                    }
                    questions = questionService.getByCategoryId(categoryId);
                    break;
                case WRONG_QUESTION:
                    questions = questionService.getWrongQuestions(user.getId());
                    break;
                default:
                    return Result.error("无效的训练模式");
            }

            if (questions.isEmpty()) {
                return Result.error("当前没有可练习的题目");
            }

            return Result.success(questions);
        } catch (IllegalArgumentException e) {
            return Result.error("无效的训练模式");
        }
    }
}
